<?php
/*
 * @Author       : ZengHao
 * @Date         : 2023-12-26 22:57:06
 * @LastEditors  : ZengHao
 * @LastEditTime : 2024-02-24 20:12:42
 * @FilePath     : /inc/functions/el-seo.php
 * @Description  : SEO 工具
 * Copyright 2023 www.exehub.com, All Rights Reserved. 
 * 2023-12-26 22:57:06
 */

//API推送给必应
if (_opz('bing_index_now')) {
    function el_bing_api($post_ID, $post, $update)
    {
        if (wp_is_post_revision($post_ID) || wp_is_post_autosave($post_ID)) {
            return;
        }
        // 已经推送的，就不需要再次推送了
        if (get_post_meta($post_ID, 'Bingsubmit', true) == 1)
            return;
        if ('publish' === $post->post_status) {
            if ('post' === $post->post_type) {
                $bing_website = _opz('bing_website');
                $bing_token = _opz('bing_token');
                $urls = '{ "siteUrl":' . $bing_website . ',"url":"' . get_permalink($post_ID) . '" }';
                $api = 'https://ssl.bing.com/webmaster/api.svc/json/SubmitUrl?apikey=' . $bing_token;
                $httpheard = array('Content-Type: application/json', 'charset=utf-8');
                $ch = curl_init();
                $options = array(
                    CURLOPT_URL => $api,
                    CURLOPT_POST => true,
                    CURLOPT_RETURNTRANSFER => true,
                    CURLOPT_POSTFIELDS => $urls,
                    CURLOPT_HTTPHEADER => $httpheard,
                );
                curl_setopt_array($ch, $options);
                $result = curl_exec($ch);
                add_post_meta($post_ID, 'Bingsubmit', 1, true);
                curl_close($ch);
            }
        }
    }
    add_action('save_post', 'el_bing_api', 10, 3);
}


//百度主动推送
if (_opz('el_baidu_push_js')) {
    function el_baidu_submit($post_ID)
    {
        $WEB_TOKEN = _opz('xzh_post_token');
        $WEB_DOMAIN = home_url();
        //已成功推送的文章不再推送
        if (get_post_meta($post_ID, 'Baidusubmit', true) == 1)
            return;
        $url = get_permalink($post_ID);
        $api = 'http://data.zz.baidu.com/urls?site=' . $WEB_DOMAIN . '&token=' . $WEB_TOKEN;
        $request = new WP_Http;
        $result = $request->request($api, array('method' => 'POST', 'body' => $url, 'headers' => 'Content-Type: text/plain'));
        $result = json_decode($result['body'], true);
        //如果推送成功则在文章新增自定义栏目Baidusubmit，值为1
        if (array_key_exists('success', $result)) {
            add_post_meta($post_ID, 'Baidusubmit', 1, true);
        }
    }
    add_action('publish_post', 'el_baidu_submit', 0);
}


//WordPress 神马 MIP 数据提交代码
if (_opz('el_sm_push_js')) {
    add_action('save_post', 'el_sm_mip_add', 10, 3);
    function el_sm_mip_add($post_id, $post, $update)
    {
        if ($post->post_status != 'publish')
            return;
        $api = 'http://data.zhanzhang.sm.cn/push?site=&user_name=&resource_name=mip_add&token=' . _opz('sm_token');
        //请到神马站长平台 http://zhanzhang.sm.cn/open/mip 中复制接口调用地址过来即可
        $response = wp_remote_post($api, array(
            'headers' => array('Accept-Encoding' => '', 'Content-Type' => 'text/plain'),
            'sslverify' => false,
            'blocking' => false,
            'body' => get_permalink($post_id)
        ));
    }
}

// 开启统计分析
if (_opz('analytics_s',false)) {
    // 百度统计分析
    function baidu_tongji()
    {
        $id = _opz('hm_baidu_token');
        $code = '';
        if ($id) {
            $code = '
            <script type="text/javascript">
                var _hmt = _hmt || [];
                (function () {
                    var hm = document.createElement("script");
                    hm.src = "https://hm.baidu.com/hm.js?' . $id . '";
                    hm.setAttribute("async", "true");
                    document.getElementsByTagName("head")[0].appendChild(hm);
                })();
            </script>
            ';
        }
        return $code;
    }
    // 谷歌统计分析
    function google_analytics()
    {
        $id = _opz('hm_google_token');
        $code = '';
        if ($id) {
            $code = '
            <script>
            (function(i,s,o,g,r,a,m){i["GoogleAnalyticsObject"]=r;i[r]=i[r]||function(){
                (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
                m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
                })(window,document,"script","https://www.google-analytics.com/analytics.js","ga");
            
                ga("create", "' . $id . '", "auto")
            
            </script>
            ';
        }
        return $code;
    }

    // 添加统计代码到footer
    add_action('wp_footer', 'el_analytics_footer', 97);
    function el_analytics_footer()
    {
        $trackcode = "<!--ANALYTICS_BD_START-->" . baidu_tongji() . "<!--ANALYTICS_BD_START-->";
        $trackcode .= "<!--ANALYTICS_GOOGLE_START-->" . google_analytics() . "<!--ANALYTICS_GOOGLE_START-->";

        echo $trackcode;
    }
}

// 标签自动内链 存在BUG 在 php8版本
// if (_opz('auto_tag_link',false)) {
//     /**
//      * Replace text by link to tag
//      *
//      * @param string $content
//      *
//      * @return string
//      */
//     //连接数量
//     $match_num_from = _opz('match_num_from'); //一个关键字少于多少不替换
//     $match_num_to = _opz('match_num_to'); //一个关键字最多替换次数
//     //连接到WordPress的模块
//     add_filter('the_content', 'tag_link', 1);
//     //按长度排序
//     function tag_sort($a, $b)
//     {
//         if ($a->name == $b->name)
//             return 0;
//         return (strlen($a->name) > strlen($b->name)) ? -1 : 1;
//     }
//     //改变标签关键字
//     function tag_link($content)
//     {
//         global $match_num_from, $match_num_to;
//         $posttags = get_the_tags();
//         if ($posttags) {
//             usort($posttags, "tag_sort");
//             foreach ($posttags as $tag) {
//                 $link = get_tag_link($tag->term_id);
//                 $keyword = $tag->name;
//                 //连接代码
//                 $cleankeyword = stripslashes($keyword);
//                 $url = "<a href=\"$link\" title=\"" . str_replace('%s', addcslashes($cleankeyword, '$'), __('查看所有文章关于 %s')) . "\"";
//                 $url .= 'target="_blank"';
//                 $url .= ">" . addcslashes($cleankeyword, '$') . "</a>";
//                 $limit = rand($match_num_from, $match_num_to);
//                 //不连接的代码
//                 $content = preg_replace('|(<a[^>]+>)(.*)(' . $ex_word . ')(.*)(</a[^>]*>)|U' . $case, '$1$2%&&&&&%$4$5', $content);
//                 $content = preg_replace('|(<img)(.*?)(' . $ex_word . ')(.*?)(>)|U' . $case, '$1$2%&&&&&%$4$5', $content);
//                 $cleankeyword = preg_quote($cleankeyword, '\'');
//                 $regEx = '\'(?!((<.*?)|(<a.*?)))(' . $cleankeyword . ')(?!(([^<>]*?)>)|([^>]*?</a>))\'s' . $case;
//                 $content = preg_replace($regEx, $url, $content, $limit);
//                 $content = str_replace('%&&&&&%', stripslashes($ex_word), $content);
//             }
//         }
//         return $content;
//     }

// }

// 网友的head标签的初始化
function el_head(){
    $current_url = home_url(add_query_arg(array())); //当前url
    $home_url = home_url(); //当前url
    $favicon = _opz('favicon'); //网站的图标
    $touch_icon = _opz('touch_icon'); //网站的图标
    $lang = esc_attr(get_bloginfo('language')); //网站的语言
    $author = _opz('basic_name'); //当前文章作者
    $keywords = _opz('keywords'); //关键词
    $description = _opz('description'); //描述
    $title = el_page_title();
    $meta = '
    <meta name="bing-analysis-id" content="1k1f2z1f2t3a2y">
	<meta charset="utf-8">
	<title>' . $title . '</title>
	<meta name="author" content="' . $author . '">
	<meta name="copyright" content="' . $author . '">
	<meta name="format-detection" content="telephone=no">
    <link rel="canonical" href="'.esc_url($home_url).'"/>
    <link rel="alternate" href="'.esc_url($home_url).'">
	<meta property="og:type" content="website">
	<meta property="og:title" content="' . $title . '">
	<meta property="og:url" content="' . esc_url($current_url)  . '">
	<meta property="og:site_name" content="' . $title . '">
	<meta property="og:locale" content="' . $lang . '">
	<meta property="og:image" content="' . $favicon . '">
	<meta property="article:author" content="' . $author . '">
	<meta name="twitter:card" content="summary">
    <meta name=twitter:title content="' . $title . '">
	<meta name="twitter:image" content="' . $favicon . '">
    <meta name="description" content="' . $description . '">
    <meta name="keywords" content="' . $keywords . '">
	<link rel="shortcut icon" href="' . $favicon . '">
    <link rel="apple-touch-icon" href="' . $touch_icon . '">';


    echo $meta;
}

/**
 * 主题的页面动态标题
 */
function el_page_title()
{
    $blog_info =get_bloginfo('name');
    $home_title = _opz('hometitle',$blog_info );
    $connector = _opz('connector', '-');
    //判断如果是首页
    if (is_home()) {
        // 获取主题设置中的值，Seo开关打开，说明用户自定义了SEO，需要我们读取
        $title = $home_title;
    } elseif (is_single() || is_page()) {
        //TODO:文章或者页面自定义seo设置的读取
        if (_opz('el_seo_s')) {
            $title = _opz('seo_title_style') == 'front' ? ($home_title . $connector . get_the_title()) : (get_the_title() . $connector . $home_title);
        } else {
            $title = get_the_title();
        }
    } elseif (is_category()) {
        $cat_ID  = get_queried_object_id();
        $cat_tit = _get_tax_meta($cat_ID, 'title');
        if ($cat_tit && (_opz('el_seo_s'))) {
            $title = $cat_tit;
            $title = _opz('seo_title_style') == 'front' ? ($home_title . $connector . $cat_tit) : ($cat_tit . $connector . $home_title);
        }else{
            $title = _opz('seo_title_style') == 'front' ? ($home_title . $connector . single_cat_title('', false)) : (single_cat_title('', false) . $connector . $home_title);
        }
    } elseif (is_tag()) {
        //TODO:标签的自定义SEO读取
        if (_opz('el_seo_s')) {
            $title = _opz('seo_title_style') == 'front' ? ($home_title . $connector . single_cat_title('', false)) : (single_cat_title('', false) . $connector . $home_title);
        } else {
            $title = single_cat_title('', false);
        }
    } elseif (is_author()) {
        if (_opz('el_seo_s')) {
            $title = _opz('seo_title_style') == 'front' ? ($home_title . $connector . get_the_author() . '的文章') : (get_the_author() . '的文章' . $connector . $home_title);
        } else {
            $title = get_the_author() . '的文章';
        }
    } elseif (is_search()) {
        $title = el_get_search_keywords() . '-搜索结果';
    }else{
        $title = '页面';
    }
    return $title;
}

/**
 * 主题自定义head代码
 */
function el_custom_head()
{
    $css_code = '';
    $fonts = '';
    if (_opz('css_code')) {
        $css_code = _opz('css_code');
    }
    $fonts_url = _opz('custom_fonts_link') ? _opz('custom_fonts_link') : (EL_THEME_URI . '/assets/fonts/OPPOSans-Regular.woff2');
    $fonts = '@font-face {font-family: "OPPOSans";src:url("' . $fonts_url . '")format("woff2");font-display: swap;}* {font-family: "OPPOSans" !important;}';
    echo '<style type="text/css">';
    echo $css_code . $fonts;
    echo '</style>';
}

function el_head_css(){
    $styles ='';
    $styles .= '.enlighter-default .enlighter{max-height:' . _opz('highlight_maxheight') . 'px;overflow-y:auto !important;}';
    if ($styles) {
        echo '<style>' . $styles . '</style>';
    }
}